package com.easybuilder.common.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeMessage.RecipientType;

import com.sun.mail.util.MailSSLSocketFactory;

    public class EmailUtil {
        private String host; // 邮箱服务器
        private String uid; // 发件人邮箱
        private String key; // 发件人邮箱授权码
        Properties props;
        // 发件人昵称
        private static  String nickName = "易构平台";
        static {
            try {
                nickName = MimeUtility.encodeText("【易构平台】");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        /**
         * 发送文本邮件，如果发送给多人，可用","对收件邮箱进行分隔。
         * @param toEmail 收件人邮箱
         * @param title 标题
         * @param content 内容
         */
        public void sendText (String toEmail, String title, String content) {
            Properties props = this.getProperties();
            Session session = Session.getInstance(props);
            Message message = new MimeMessage(session);
            try {
                // 设置发件人信息
                message.setFrom(new InternetAddress(nickName +" <"+uid+">"));
                // 设置收件人邮箱、邮件内容
                setReceive(toEmail, message);
                message.setSubject(title);
                message.setText("TEXT");
                message.setContent(content, "text/html;charset=utf-8");
                //ssl加密
                ssl(props);
                // 获取传输对象
                Transport transport = session.getTransport();
                // 登陆邮箱服务器
                transport.connect(host, uid, key);
                // 发送
                transport.sendMessage(message, message.getAllRecipients());
                System.out.println("发送成功!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        /**
         * 发送多附件邮件
         * @param toEmail
         * @param title
         * @param content
         */
        public void sendEmailWithFile (String toEmail, String title, String content, List<File> fileList) {
            Properties props = this.getProperties();
            Session session = Session.getInstance(props);
            Message message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(nickName +" <"+uid+">"));
                setReceive(toEmail, message); //设置收件人
                message.setSubject(title);  //设置标题
                message.setContent(content, "text/html;charset=utf-8");

                setFile(message, content, fileList); // 添加多文本内容、附件

                Transport transport = session.getTransport();
                transport.connect(host, uid, key);  //登陆

                transport.sendMessage(message, message.getAllRecipients());  // 此方式发送可以省略验证步骤
                System.out.println("发送成功!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 给消息对象添加附件
         * @param message
         */
        private void setFile(Message message, String content, List<File> fileList) {
            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            try {
                if (content != null && !"".equals(content)) {
                    BodyPart contentBodyPart = new MimeBodyPart();
                    contentBodyPart.setContent(content, "text/html;charset=utf-8");
                    multipart.addBodyPart(contentBodyPart);
                }
                for (File file : fileList) {
                    if (file.exists()) { // 如果附件存在执行添加，否则报空指针
                        // 附件部分
                        BodyPart messageBodyPart = new MimeBodyPart();
                        DataSource source = new FileDataSource(file);
                        messageBodyPart.setDataHandler(new DataHandler(source));
                        messageBodyPart.setFileName(MimeUtility.encodeWord(file.getName())); // 避免文件名中文乱码
                        multipart.addBodyPart(messageBodyPart);
                    }
                }

                // 发送完整消息
                message.setContent(multipart);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 设置邮箱服务器
         * @return 邮箱服务器配置信息
         */
        private Properties getProperties () {
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.auth", "true");
            return props;
        }


        /**
         * 自动设置单人/多人发送邮件
         * @param toEmail
         * @param message
         */
        private void setReceive(String toEmail, Message message) {
            if (toEmail != null && !"".equals(toEmail)) {
                try {
                    if (toEmail.indexOf(",") != -1) { // 发送给多人
                        InternetAddress[] address = InternetAddress.parse(toEmail);
                        message.addRecipients(RecipientType.TO, address);
                    } else { // 发送给单人
                        message.setRecipient(RecipientType.TO, new InternetAddress(toEmail));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * ssl加密处理
         * @param props
         */
        private void ssl (Properties props) {
            MailSSLSocketFactory sf;
            try {
                sf = new MailSSLSocketFactory();
                sf.setTrustAllHosts(true);
                props.put("mail.smtp.ssl.enable", "true");
                props.put("mail.smtp.ssl.socketFactory", sf);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }

        }


        public EmailUtil() {

        }

        public EmailUtil(String host, String uid, String key) {
            super();
            this.host = host;
            this.uid = uid;
            this.key = key;
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

    }


